'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useFileUpload } from '@/api/uploads'
import { toast } from 'sonner'
import { getRouteApi, useRouter } from '@tanstack/react-router'
import { Progress } from '@/components/ui/progress'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

interface Props {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function UploadsActionDialog({ open, onOpenChange }: Props) {
  const router = useRouter()
  const routeApi = getRouteApi('/_authenticated/uploads/')
  const { uploadDict } = routeApi.useLoaderData()
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [selectedCategory, setSelectedCategory] = useState<string>('')
  const [uploadProgress, setUploadProgress] = useState(0)
  const fileUpload = useFileUpload()

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      setSelectedFile(event.target.files[0])
    }
  }

  const handleUpload = () => {
    if (!selectedFile) {
      toast.error('Please select a file to upload.')
      return
    }
    if (!selectedCategory) {
      toast.error('Please select a category.')
      return
    }

    fileUpload.mutate(
      {
        file: selectedFile,
        category: selectedCategory,
        onProgress: (percent) => {
          setUploadProgress(percent)
        },
      },
      {
        onSuccess: () => {
          toast.success('File uploaded successfully!')
          onOpenChange(false)
          setSelectedFile(null)
          setUploadProgress(0)
          setSelectedCategory('')
          router.invalidate()
        },
        onError: () => {
          setUploadProgress(0)
        }
      }
    )
  }

  const handleOpenChange = (isOpen: boolean) => {
    if (!isOpen) {
      setSelectedFile(null)
      setUploadProgress(0)
      setSelectedCategory('')
    }
    onOpenChange(isOpen)
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className='sm:max-w-md'>
        <DialogHeader>
          <DialogTitle>Upload File</DialogTitle>
          <DialogDescription>
            Select a file and category to upload.
          </DialogDescription>
        </DialogHeader>
        <div className='grid gap-4 py-4'>
          <div className='grid grid-cols-4 items-center gap-4'>
            <Label htmlFor='category-select' className='text-right'>
              Category
            </Label>
            <Select onValueChange={setSelectedCategory} value={selectedCategory}>
              <SelectTrigger className='col-span-3'>
                <SelectValue placeholder="Select a category" />
              </SelectTrigger>
              <SelectContent>
                {uploadDict.map((item) => (
                  <SelectItem key={item.value} value={item.value}>
                    {item.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className='grid grid-cols-4 items-center gap-4'>
            <Label htmlFor='file-upload' className='text-right'>
              File
            </Label>
            <Input
              id='file-upload'
              type='file'
              className='col-span-3'
              onChange={handleFileChange}
            />
          </div>
          {fileUpload.isPending && (
            <Progress value={uploadProgress} className='w-full' />
          )}
        </div>
        <DialogFooter>
          <Button
            type='button'
            onClick={handleUpload}
            disabled={!selectedFile || !selectedCategory || fileUpload.isPending}
          >
            {fileUpload.isPending ? 'Uploading...' : 'Upload'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
